import { createAsyncThunk, createEntityAdapter, createSlice, createSelector } from '@reduxjs/toolkit';
import { WallpaperType } from '@interfaces';
import { baseURL } from '@config';
import { serialize } from '@helpers';
import { RootState } from '@src/store';

const wallpaperTypeAdapter = createEntityAdapter({
  selectId: (wallpaperType: WallpaperType) => wallpaperType._id,
});

export const WALLPAPERTYPE_FEATURE_KEY = 'wallpapertype';

export const loadWallpaperTypes = createAsyncThunk(`${WALLPAPERTYPE_FEATURE_KEY}/list`, (payload: object, thunkAPI) => {
  fetch(`${baseURL}/api/wallpapertype${serialize(payload)}`)
    .then(response => response.json())
    .then(response => {
      thunkAPI.dispatch(addMany(response?.data?.rows || []));
    })
});

const wallpaperTypeSlice = createSlice({
  name: WALLPAPERTYPE_FEATURE_KEY,
  initialState: wallpaperTypeAdapter.getInitialState([]),
  reducers: {
    addOne: wallpaperTypeAdapter.addOne,
    addMany: {
      reducer: wallpaperTypeAdapter.addMany,
      prepare: (wallpaperTypes: WallpaperType[]) => {
        if (!wallpaperTypes.find(wt => wt.name === '全部')) {
          wallpaperTypes.unshift({
            key: '',
            _id: '',
            title: '全部',
            name: 'all',
            createdAt: new Date().toLocaleString(),
            updatedAt: new Date().toLocaleString(),
            path: '',
            icon: ''
          });
        }
        return {
          payload: wallpaperTypes,
        };
      }
    }
  },
});

const { selectAll } = wallpaperTypeAdapter.getSelectors();

export const selectWallpaperTypes = createSelector((state: RootState) => state[WALLPAPERTYPE_FEATURE_KEY], selectAll);

export const { addOne, addMany } = wallpaperTypeSlice.actions;

export default wallpaperTypeSlice.reducer;
